<template>
  <div class="auth-resource">
    <el-row justify="center">
      <el-col :span="16">
        <el-form
          ref="formRef"
          :model="formModel"
          label-width="100px"
          label-position="left"
          :rules="formRules"
        >
          <div class="sub-title">企业基本资料</div>
          <div class="form-1">
            <el-row :gutter="48">
              <el-col :span="12">
                <el-form-item label="企业全称" prop="enterpriseName">
                  <el-input
                    v-model="formModel.enterpriseName"
                    maxlength="50"
                    placeholder="请输入企业全称"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="英文全称" prop="enterpriseNameEn">
                  <el-input
                    v-model="formModel.enterpriseNameEn"
                    maxlength="100"
                    placeholder="请输入企业英文全称"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业地址" prop="address">
                  <el-input
                    v-model="formModel.address"
                    maxlength="100"
                    placeholder="请输入企业地址"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="sub-title">企业营业信息</div>
          <div class="form-1">
            <el-row :gutter="48">
              <el-col :span="12">
                <el-form-item label="证件号码" prop="businessLicenseNo">
                  <el-input
                    v-model="formModel.businessLicenseNo"
                    maxlength="50"
                    placeholder="请输入证件号码"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item>
                  <template #label>
                    <span class="red-star">企业证件</span>
                  </template>
                  <div>
                    <div class="company-cert">
                      请上传证件扫描件或照片，文件大小不能超过10MB，格式为png、jpeg、jpg、gif、bmp。如需提交更多证件，请在“其他证件”上传处上传
                    </div>
                    <div class="upload-comp">
                      <uploadCert
                        title="营业执照"
                        :requiredFlag="true"
                        v-model:imgThumbnail="formModel.business.thumbnail"
                        v-model:imgFileId="formModel.business.fileId"
                      ></uploadCert>
                      <uploadCert
                        title="其他证件一"
                        class="margin-left-16"
                        v-model:imgThumbnail="formModel.business1.thumbnail"
                        v-model:imgFileId="formModel.business1.fileId"
                      ></uploadCert>
                      <uploadCert
                        title="其他证件二"
                        class="margin-left-16"
                        v-model:imgThumbnail="formModel.business2.thumbnail"
                        v-model:imgFileId="formModel.business2.fileId"
                      ></uploadCert>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item>
                  <template #label>
                    <span class="red-star">法人证件</span>
                  </template>
                  <div class="person-cert">
                    <div class="cert-top">
                      <div class="cert-wrap">
                        <uploadCert
                          title="身份证正面"
                          :requiredFlag="true"
                          v-model:imgThumbnail="formModel.legal1.thumbnail"
                          v-model:imgFileId="formModel.legal1.fileId"
                        ></uploadCert>
                        <uploadCert
                          title="身份证反面"
                          :requiredFlag="true"
                          class="margin-left-16"
                          v-model:imgThumbnail="formModel.legal2.thumbnail"
                          v-model:imgFileId="formModel.legal2.fileId"
                        ></uploadCert>
                      </div>
                      <div class="tips margin-left-16">
                        请上传本人手持身份证人像面上半身照片，确保着装整齐
                        证件信息清晰可见不能被遮挡，持证人五官清晰可见，手臂完整露出
                        核实手持证件内容与原件方向一致、对焦身份证进行拍照
                      </div>
                    </div>
                    <div class="cert-bottom">
                      <div class="cert-bottom-item">
                        <div class="title">手持身份证人像面（样例）</div>
                        <img src="@/assets/images/girl_z.png" />
                      </div>
                      <div class="cert-bottom-item">
                        <div class="title">手持身份证国徽面（样例）</div>
                        <img src="@/assets/images/gril_f.png" />
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="sub-title">企业联系人信息</div>
          <div class="form-1">
            <el-row :gutter="48">
              <el-col :span="12">
                <el-form-item label="姓名" prop="contactName">
                  <el-input
                    v-model="formModel.contactName"
                    maxlength="30"
                    placeholder="请输入姓名"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号码" prop="contactIDCardNo">
                  <el-input
                    v-model="formModel.contactIDCardNo"
                    maxlength="30"
                    placeholder="请输入身份证号码"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="contactPhone">
                  <el-input
                    v-model="formModel.contactPhone"
                    maxlength="11"
                    placeholder="请输入手机号"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="contactEmail">
                  <el-input
                    v-model="formModel.contactEmail"
                    maxlength="30"
                    placeholder="请输入邮箱"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label=" ">
                  <el-button
                    type="primary"
                    @click="confirmBind"
                    class="btnConfirm"
                    :loading="loading"
                    v-if="showSubmit"
                  >
                    提交认证
                  </el-button>
                  <el-button
                    type="primary"
                    @click="confirmBind"
                    class="btnConfirm"
                    :loading="loading"
                    v-if="!showSubmit && !authPass"
                  >
                    保存
                  </el-button>
                  <!-- <el-button
                    @click="cancelBind"
                    class="btnCancer"
                    v-if="!showSubmit && !update"
                    >返回上一页</el-button
                  > -->
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
const appStore = MyStore.useApp();
const { loginUser } = storeToRefs(appStore);
import { ElMessage } from "element-plus";
import { addEnterprise, editEnterprise, companyDetail } from "@/service/dp.ts";
import uploadCert from "./uploadCert.vue";
const timer: any = ref(null);
const props = defineProps({
  showSubmit: false,
  update: false,
  authPass: true,
});
const emit = defineEmits(["submitData"]);
const formRef: any = ref(null);
const loading: any = ref(false);
const formModel: any = ref({
  enterpriseName: "",
  enterpriseNameEn: "",
  address: "",
  businessLicenseNo: "",
  businessLicenseCard: [],
  business: { fileId: "", thumbnail: "", sortCode: 0 },
  business1: { fileId: "", thumbnail: "", sortCode: 1 },
  business2: { fileId: "", thumbnail: "", sortCode: 2 },
  legalPersonCard: [],
  legal1: { fileId: "", thumbnail: "", sortCode: 0 },
  legal2: { fileId: "", thumbnail: "", sortCode: 1 },
  contactName: "",
  contactIDCardNo: "",
  contactPhone: "",
  contactEmail: "",
});
const formRules: any = ref({
  enterpriseName: [
    {
      required: true,
      message: "请输入企业名称",
      trigger: "blur",
    },
  ],
  address: [
    {
      required: true,
      message: "请输入企业地址",
      trigger: "blur",
    },
  ],
  businessLicenseNo: [
    {
      required: true,
      message: "请输入证件号码",
      trigger: "blur",
    },
  ],
  contactName: [
    {
      required: true,
      message: "请输入联系人姓名",
      trigger: "blur",
    },
  ],
  contactIDCardNo: [
    {
      required: true,
      message: "请输入联系人身份证号码",
      trigger: "blur",
    },
    {
      pattern:
        /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/,
      message: "身份证号码格式不正确",
      trigger: "blur",
    },
  ],
  contactPhone: [
    {
      required: true,
      message: "请输入联系人手机号码",
      trigger: "blur",
    },
    {
      pattern: /^1[3,4,5,6,7,8,9][0-9]{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  contactEmail: [
    {
      required: true,
      message: "请输入联系人邮箱",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱格式",
      trigger: "blur",
    },
  ],
});

// 校验营业执照、身份证正、反面
function validateBusiness(arr: any) {
  let smooth: any = true;
  for (let i = 0; i < arr.length; i++) {
    if (!arr[i].fileId) {
      smooth = false;
      ElMessage.error({
        message: arr[i].message,
      });
      break;
    }
  }
  return smooth;
}

// 保存
function confirmBind() {
  if (
    !validateBusiness([
      { ...formModel.value.business, message: "请上传营业执照!" },
      { ...formModel.value.legal1, message: "请上传身份证正面!" },
      { ...formModel.value.legal2, message: "请上传身份证反面!" },
    ])
  ) {
    return;
  }
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const params: any = { ...formModel.value };
      params.businessLicenseCard = [
        params.business,
        params.business1,
        params.business2,
      ];
      params.legalPersonCard = [params.legal1, params.legal2];
      ["business", "business1", "business2", "legal1", "legal2"].forEach(
        (key) => {
          delete params[key];
        }
      );
      if (props.update) {
        params.id = loginUser.value.orgId;
      }
      loading.value = true;
      let res: any = null;
      if (!params.id) {
        res = await addEnterprise(params);
      } else {
        res = await editEnterprise(params);
      }

      if (res.code == 200) {
        emit("submitData");
        ElMessage.success({
          message: props.update ? "修改认证资料成功!" : "提交认证资料成功!",
        });
      } else {
        ElMessage.error({
          message: res.msg,
        });
      }
      loading.value = false;
    }
  });
}

// 获取详情
async function getCompanyDetail(id: any) {
  const res: any = await companyDetail({ id });
  if (res.code == 200) {
    formModel.value = {
      ...res.data,
      business: res.data.businessLicenseCard[0],
      business1: res.data.businessLicenseCard[1] || {},
      business2: res.data.businessLicenseCard[2] || {},
      legal1: res.data.legalPersonCard[0],
      legal2: res.data.legalPersonCard[1],
    };
  } else {
    ElMessage.error({
      message: res.msg,
    });
  }
}

onMounted(() => {
  if (props.update) {
    timer.value = setTimeout(() => {
      getCompanyDetail(loginUser.value.orgId);
    }, 100);
  }
});

onUnmounted(() => {
  timer.value = null;
});
</script>

<style scoped lang="scss">
.red-star::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.margin-left-16 {
  margin-left: 16px;
}
.auth-resource {
  // padding: 48px 195px 24px 197px;
  padding-top: 48px;
  background-color: #ffffff;
  .sub-title {
    margin-bottom: 24px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 14px;
    color: #000000;
    line-height: 21px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    padding-left: 14px;
    height: 21px;
    border-left: 2px solid rgba(0, 0, 0, 0.9);
  }
  .form-1 {
    padding-left: 16px;
  }
  .company-cert {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.4);
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .upload-comp {
    display: flex;
  }

  .person-cert {
    display: flex;
    flex-direction: column;
    .cert-wrap {
      display: flex;
    }
    .tips {
      display: flex;
      align-items: center;
      max-width: 420px;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.4);
      line-height: 16px;
      font-style: normal;
      text-transform: none;
    }
  }

  .cert-top {
    display: flex;
  }

  .cert-bottom {
    margin-top: 16px;
    display: flex;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #000000;
    text-align: left;
    font-style: normal;
    text-transform: none;
    img {
      margin-top: 8px;
    }
  }
}
</style>
